﻿using G = Gym.Domain.GymAggregate;
using MediatR;
using ErrorOr;
using Gym.Application.Common.Interfaces;

namespace Gym.Application.Gyms.Commands.CreateGym
{
    public class CreateGymCommandHandler : IRequestHandler<CreateGymCommand, ErrorOr<G.Gym>>
    {
        private readonly ISubscriptionsRepository _subscriptionRepository;

        public CreateGymCommandHandler(ISubscriptionsRepository subscriptionRepository)
        {
            _subscriptionRepository = subscriptionRepository;
        }

        public async Task<ErrorOr<G.Gym>> Handle(CreateGymCommand request, CancellationToken cancellationToken)
        {
            var subscription = await _subscriptionRepository.GetByIdAsync(request.SubscriptionId);

            if (subscription == null)
            {
                return Error.NotFound(description:"没有找到订阅信息");
            }

            var gym = new G.Gym(
                name: request.Name,
                maxRooms: subscription.GetMaxRooms(),
                subscriptionId: request.SubscriptionId);

            var addGymResult = subscription.AddGym(gym);

            if (addGymResult.IsError)
            {
                return addGymResult.Errors;
            }

            await _subscriptionRepository.UpdateAsync(subscription);

            return gym;
        }
    }
}
